package com.yuntian.service.Impl;

import com.yuntian.dto.ProductOrderDataDto;
import com.yuntian.exception.BusinessException;
import com.yuntian.exception.MonthIllegalException;
import com.yuntian.exception.NoDataException;
import com.yuntian.mapper.ProductOrderDataMapper;
import com.yuntian.service.ProductMonthReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;


@Service
public class ProductMonthReportServiceImpl implements ProductMonthReportService {
    @Autowired
    private ProductOrderDataMapper productOrderDataMapper;
    private static final Logger logger = LoggerFactory.getLogger(CustomerMonthReportServiceImpl.class);


    @Override
    public List<ProductOrderDataDto> getProductOrderData(Integer year, Integer month) {





            // 1. 处理year/month为null：默认使用系统当前年月（系统月次）
            LocalDate now = LocalDate.now();
            if (year == 0) year = now.getYear();
            if (month == 0) month = now.getMonthValue();

            validateMonth(year, month, now);


            try {
                // 3. 查询当月受注编码列表
                List<String> orderCodeList =productOrderDataMapper.selectProductCodeByMonth(year, month);
                System.out.println(orderCodeList);

                if (orderCodeList.isEmpty()) {

                    throw new NoDataException("M103001E：当月顧客受注情報がありません。");
                }

                // 4. 查询客户受注明细（已按受注额降序，含序号）
                List<ProductOrderDataDto> orderDataList = productOrderDataMapper.selectByProductCode(orderCodeList);
                if (orderDataList.isEmpty()) {
                    throw new NoDataException("M103001E：当月顧客受注情報がありません。");
                }

                return orderDataList;
            } catch (Exception e) {
                logger.error("SQL执行异常，原始错误：", e);  // 打印堆栈信息
                // 5. 统一处理SQL异常
                if (e instanceof NoDataException || e instanceof MonthIllegalException) {

                    throw e; // 已知业务异常直接抛出
                }
                throw new BusinessException("M00001E：SQL実行例外が発生しました。");
            }
        }


        private void validateMonth(Integer year, Integer month, LocalDate now) {
            // 系统当前年月
            int currentYear = now.getYear();
            int currentMonth = now.getMonthValue();
            // 前年度当月
            int lastYear = currentYear - 1;

            // 校验1：印刷月次 > 系统月次（如2024-11 > 2024-10）
            if (year > currentYear || (year == currentYear && month > currentMonth)) {
                throw new MonthIllegalException("M103002E：印刷月次が不正です。");
            }


        }
}

